#include "calculatorview.h"
#include "ui_calculatorview.h"
#include <QDebug>

CalculatorView::CalculatorView(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::CalculatorView)
    , isInput(false)
{
    ui->setupUi(this);

    this->setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint);
    this->setFixedSize(this->width(), this->height());
    // setMaximumSize(this->width(), this->height());

    QIcon icon = QIcon(":/res/images/icons/favicon-32x32.png");
    this->setWindowIcon(icon);

    ui->editExpr->setReadOnly(true);
    ui->editExpr->setAlignment(Qt::AlignRight);
    ui->editResult->setReadOnly(true);
    ui->editResult->setAlignment(Qt::AlignRight);

    ui->editExpr->clear();
    ui->editResult->setText("0");
}

CalculatorView::~CalculatorView()
{
    delete ui;
}

void CalculatorView::appendNumber(const QString &s)
{
    if (isError()) {
        clear();
    }

    auto text = ui->editResult->text();
    auto expr = ui->editExpr->text();

    if (!isInput) {
        text = "0";
    }

    if (text == "0") {
        if (s == ".") {
            text = "0.";
        }
        else {
            text = s;
        }
    } else {
        if (s == "."){
            if(text.back() != '.') {
                text.append(".");
            }
        } else if (s == "-") {
            if (text.front() != '-') {
                text.prepend("-");
            } else {
                text.remove(0, 1);
            }
        } else {
            text.append(s);
        }
    }
    ui->editResult->setText(text);
    if (expr.endsWith("=")) {
        ui->editExpr->setText("");
    }
    isInput = true;
}

void CalculatorView::appendOperator(const QString &op)
{
    lastOp = op;
    auto expr = ui->editExpr->text();
    auto curr = ui->editResult->text();
    lastNumber = curr;

    if (expr.endsWith("=")) {
        expr = "";
    }
    if (!expr.isEmpty()) {
        if (isInput) {
            if (curr.startsWith("-")) {
                expr += "(" + curr + ")"+ op;
            } else {
                expr += curr + op;
            }
        } else {
            expr.replace(expr.size() - 1, 1, op);
        }
    } else {
        expr = curr + op;
    }

    ui->editExpr->setText(expr);
    isInput = false;
}

void CalculatorView::clearLastOp()
{
    lastNumber = "0";
    lastOp.clear();
}

void CalculatorView::clear()
{
    clearE();
    ui->editExpr->clear();
}

void CalculatorView::clearE()
{
    setError(Calculator::Error::ERR_OK);
    ui->editResult->setText("0");
    currNumber = "0";
    isInput = false;
    clearLastOp();
}

void CalculatorView::setError(Calculator::Error err)
{
    mErrorCode = err;
}

bool CalculatorView::isError() const
{
    return mErrorCode != Calculator::Error::ERR_OK;
}

QString CalculatorView::getErrorMsg() const
{
    if (mErrorCode == Calculator::Error::ERR_DIVIDE_ZERO) {
        return QString("除数不能是0");
    } else {
        return QString("错误");
    }
}


void CalculatorView::on_btnC_clicked()
{
    clear();
}


void CalculatorView::on_btnCE_clicked()
{
    clearE();
}


void CalculatorView::on_btnDel_clicked()
{
    if (isError()) {
        clear();
        return;
    }

    if (!isInput) {
        return;
    }

    auto text = ui->editResult->text();
    if (!text.isEmpty()) {
        text.resize(text.size() - 1);
    }
    if (text == "" || text == "-") {
        text = "0";
    }
    currNumber = text;
    ui->editResult->setText(text);
}


void CalculatorView::on_btnEnter_clicked()
{
    if (isError()) {
        clear();
        return;
    }

    QString expr = ui->editExpr->text();
    auto curr = ui->editResult->text();

    if (isInput && !expr.isEmpty()) {
        lastNumber = curr;
    }
    isInput = false;
    if (!lastNumber.isEmpty() && lastNumber.back() == '.') {
        lastNumber.resize(lastNumber.size() - 1);
    }

    if (expr.endsWith("=") || expr.isEmpty()) {
        if (!lastOp.isEmpty()) {
            if (lastNumber.startsWith("-")) {
                expr = curr + lastOp + "(" + lastNumber + ")";
            } else {
                expr = curr + lastOp + lastNumber;
            }
        } else {
            ui->editExpr->setText(curr + "=");
            return;
        }
    } else {
        if (curr.startsWith("-") && !expr.isEmpty()) {
            expr += "(" + curr + ")";
        } else {
            expr += curr;
        }
    }

    qDebug() << "expr: " << expr;
    auto calcStr = expr;
    calcStr.replace("÷", "/");
    Calculator calc;
    auto res = calc.exec(calcStr);
    setError(calc.errorCode());
    qDebug() << "res: " << res << ", error:" << (int)mErrorCode;
    ui->editExpr->setText(expr + "=");
    if (isError()) {
        ui->editResult->setText(getErrorMsg());
    } else {
        ui->editResult->setText(QString::number(res, 'g', 16));
    }
}


void CalculatorView::on_btnNP_clicked()
{
    if (isError()) {
        return;
    }

    auto curr = ui->editResult->text();

    if (isInput) {
        if (curr == "0") return;
        appendNumber("-");
        return;
    }

    if (curr != "0") {
        if (curr.startsWith("-")) {
            curr.remove(0, 1);
        } else {
            curr.prepend("-");
        }
        ui->editResult->setText(curr);
    }
    auto expr = ui->editExpr->text();
    if (expr.endsWith("=")) {
        ui->editExpr->setText(curr + "=");
    }
}


void CalculatorView::on_btnDot_clicked()
{
    if (isError()) {
        return;
    }
    appendNumber(".");
}


void CalculatorView::on_btn0_clicked()
{
    appendNumber("0");
}


void CalculatorView::on_btn1_clicked()
{
    appendNumber("1");
}


void CalculatorView::on_btn2_clicked()
{
    appendNumber("2");
}


void CalculatorView::on_btn3_clicked()
{
    appendNumber("3");
}


void CalculatorView::on_btn4_clicked()
{
    appendNumber("4");
}


void CalculatorView::on_btn5_clicked()
{
    appendNumber("5");
}


void CalculatorView::on_btn6_clicked()
{
    appendNumber("6");
}


void CalculatorView::on_btn7_clicked()
{
    appendNumber("7");
}


void CalculatorView::on_btn8_clicked()
{
    appendNumber("8");
}


void CalculatorView::on_btn9_clicked()
{
    appendNumber("9");
}


void CalculatorView::on_btnAdd_clicked()
{
    if (isError()) {
        return;
    }
    appendOperator("+");
}


void CalculatorView::on_btnSub_clicked()
{
    if (isError()) {
        return;
    }
    appendOperator("-");
}


void CalculatorView::on_btnMul_clicked()
{
    if (isError()) {
        return;
    }
    appendOperator("x");
}


void CalculatorView::on_btnDiv_clicked()
{
    if (isError()) {
        return;
    }
    appendOperator("÷");
}

